import React, { Component } from 'react'
import { Col, Icon, Progress, Row, Switch } from 'antd'
import { connect } from 'react-redux'
import '../../../less/index.less'
import Menu from '../../common/menu/vertical-menu'
import UrlPattern from 'url-pattern'
import * as programActions from '../../../actions/program'
import SectionListBox from './section-list-box'
import TopicTaskBox from './topic-task-box'
import { FormattedMessage } from 'react-intl'
import {getLangFromLocalStorage} from '../../../constant/lang-util'

class Index extends Component {
  constructor (props) {
    super(props)
    this.state = {
      programId: 1,
      showSection: true
    }
  }

  componentDidMount () {
    const pattern = new UrlPattern('/program/:programId/task')
    const urlParams = pattern.match(this.props.location.pathname) || {}
    this.setState({
      programId: urlParams.programId
    }, () => {
      this.props.getTopicTasks(this.state.programId)
      this.props.getProgram(this.state.programId)
    })
  }

  onChange (checked) {
    this.setState({
      showSection: !checked
    })
  }
  getTotalTaskCount (topicsTasks) {
    if (topicsTasks.length !== 0) {
      return topicsTasks.map(topic => topic.all.length).reduce((a, b) => a + b)
    }
  }

  getAssignments (topicsTasks) {
    let result = []
    const lang = getLangFromLocalStorage()

    topicsTasks.forEach(topic => {
      topic.all.forEach(task =>
        task.assignments.forEach(assignment =>
          result.push({
            topicTitle: topic.title,
            [`topicTitle_${lang}`]: topic[`title_${lang}`],
            taskTitle: task.title,
            [`taskTitle_${lang}`]: task[`title_${lang}`],
            taskType: task.type,
            taskId: task.id,
            assignment: assignment
          })
        )
      )
    })
    return result
  }

  getFinishTaskCount (topicsTasks) {
    let result = 0
    topicsTasks.forEach(topic => {
      result += topic.finished.length + topic.excellent.length
    })
    return result
  }

  getFinishAssignmentCount (results) {
    return results.filter(item => item.assignment.status === 'finished' ||
    item.assignment.status === 'excellent').length
  }

  render () {
    const topicsTasks = this.props.topicsTasks
    const results = this.getAssignments(topicsTasks)
    const totalTaskCount = this.getTotalTaskCount(topicsTasks)
    const finishTaskCount = this.getFinishTaskCount(topicsTasks)
    const finishAssignmentCount = this.getFinishAssignmentCount(results)
    const isSectionView = this.state.showSection
    const percent = isSectionView
      ? parseFloat((finishTaskCount / totalTaskCount) * 100).toFixed(2)
      : parseFloat((finishAssignmentCount / results.length) * 100).toFixed(2)
    const isShowTasks = topicsTasks.length === 0
    const isShowIntegration = this.props.programInfo.isShowIntegration
    return (<div>
      <Row>
        <Col span={5}>
          <Menu isShowIntegration={isShowIntegration} />
        </Col>
        <Col span={19}>
          <Row>
            <Col span={8}><FormattedMessage id='当前进度' />：<FormattedMessage id='共有' />
              {isSectionView ? totalTaskCount : results.length}<FormattedMessage id='个' /> .
              <FormattedMessage id='已完成' />{isSectionView ? finishTaskCount : finishAssignmentCount}
              <FormattedMessage id='个' /></Col>
            <Col span={8}><Progress percent={Number.parseFloat(percent)} /></Col>
            <Col span={4} offset={4}>
              <Switch checkedChildren={<FormattedMessage id='作业视图' />} unCheckedChildren={<FormattedMessage id='任务卡视图' />}
                onChange={this.onChange.bind(this)} />
            </Col>
          </Row>
          {isShowTasks
          ? <div>
            <br />
            <Icon type='frown' theme='outlined' /><FormattedMessage id='没有可见的任务卡' />
          </div>
          : this.state.showSection
              ? <TopicTaskBox topicsTasks={topicsTasks} />
              : <SectionListBox results={results} />
          }
        </Col>
      </Row>
    </div>
    )
  }
}

const mapStateToProps = state => ({
  topicsTasks: state.topicsTasks,
  programInfo: state.program
})
const mapDispatchToProps = dispatch => ({
  getTopicTasks: (programId) => dispatch(programActions.getTopicTasks(programId)),
  getProgram: (programId) => dispatch(programActions.getProgramIntroduction(programId))
})

export default connect(mapStateToProps, mapDispatchToProps)(Index)
